package service;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import mapper.CommonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import pojos.common.ReplyMessage;
import pojos.sms.SmsFeedBackCode;
import pojos.sms.SmsRecord;

import java.sql.Timestamp;
import java.util.Random;

/**
 * 短信通知服务
 */
public class SmsNotifyService {

    private final Logger logger = LoggerFactory.getLogger(SmsNotifyService.class);
    private final String accessKeyId = "LTAI4FhCpbPz7sr1aXAq1b1Q";
    private final String accessKeySecret = "BImGflGpRLjUzHdRurtFwVet6vJVbt";
    private final String signName = "云道";
    private final String forgetPasswordTemplateId = "SMS_174279494";
    private final String alterPhoneNumTemplateId = "SMS_174274883";
    private final String courseNotifyTemplateId = "SMS_174274378";

    private CommonMapper commonMapper;

    @Autowired
    public SmsNotifyService(CommonMapper commonMapper) {
        this.commonMapper = commonMapper;
    }

    /**
     * 修改手机号
     */
    public ReplyMessage phoneNumVerify(String phoneNum, int type){
        String codeNum = getRandom();

        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setMethod(MethodType.POST);
        commonRequest.setDomain("dysmsapi.aliyuncs.com");
        commonRequest.setVersion("2017-05-25");
        commonRequest.setAction("SendSms");
        commonRequest.putQueryParameter("RegionId", "cn-hangzhou");
        commonRequest.putQueryParameter("PhoneNumbers", phoneNum);
        commonRequest.putQueryParameter("SignName", signName);
        commonRequest.putQueryParameter("TemplateParam", "{\"code\":\""+ codeNum +"\"}");

        if(type == 1){
            commonRequest.putQueryParameter("TemplateCode", forgetPasswordTemplateId);
        }else{
            commonRequest.putQueryParameter("TemplateCode", alterPhoneNumTemplateId);
        }

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            CommonResponse response = client.getCommonResponse(commonRequest);
            String result = response.getData();

            SmsFeedBackCode backCode = JSON.parseObject(result, SmsFeedBackCode.class);
            if(backCode.getCode().equalsIgnoreCase("ok")){
                replyMessage.setStatus(200);
                replyMessage.setInfo(codeNum);
            }else {
                replyMessage.setStatus(400);
                replyMessage.setInfo("短信发送失败！");
            }

            SmsRecord smsRecord = new SmsRecord();
            smsRecord.setPhone(phoneNum);
            smsRecord.setTime(new Timestamp(System.currentTimeMillis()));
            smsRecord.setStatus(backCode.getCode());
            smsRecord.setBiz(backCode.getBizId());
            smsRecord.setType(type);
            smsRecord.setParam("{\"code\":\""+ codeNum +"\"}");

            commonMapper.smsSendRecord(smsRecord);

            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送短信异常，手机号："+phoneNum+"，验证码："+codeNum);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }finally {
            client.shutdown();
        }
    }

    /**
     * 生成6位随机数
     */
    private String getRandom(){
        Random random = new Random();
        StringBuilder builder = new StringBuilder(6);

        for(int i=0; i<6; i++){
            builder.append(random.nextInt(10));
        }
        return builder.toString();
    }
}
